package actions;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

import modelo.Tesina;
import modelo.Usuario;
import DAO.FactoryDAO;
import DAO.TesinaDAO;
import DAO.UsuarioDAO;

// Inicio del action...

public class Login extends ActionSupport implements SessionAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private Map<String, Object> session;
	private Collection <Tesina> collTesis = new ArrayList <Tesina>();

	public String execute() {
		UsuarioDAO uDAO = FactoryDAO.getUsuarioDAO();
		Usuario u = uDAO.encontrar(getName(), getClave());

		session.put("logged-in", "true");
		session.put("perfil", u.getPerfil());
		session.put("clave", u.getClave());
		session.put("email", u.getEmail());
		session.put("telefono", u.getTelefono());
		session.put("name", u.getName());
		session.put("id", u.getId());
		session.put("usuario", u);
		session.put("contenido", "/jsp/contenido/tablaTesinasFront.jsp");

		if (u.getPerfil().equals("administrador")) {
			session.put("contenido", null);
			return "administrador";
		}
		
		TesinaDAO tesinaDAO = FactoryDAO.getTesinaDAO();
		collTesis = tesinaDAO.obtenerUltimasTesinas();
		
		return "usuario";
	}

	public void validate() {
		if (getName().equals("") && getClave().equals("")) {
			addFieldError("name", getText("global.usuarioClaveVacios"));
		} else if (getName().equals("") || getClave().equals("")) {
			if (getName().equals("")) {
				addFieldError("name", getText("global.usuarioVacio"));

			} else {
				addFieldError("clave", getText("global.claveVacia"));
			}
		}

		if (getName().compareTo("") != 0 && getClave().compareTo("") != 0) {
			UsuarioDAO uDAO = FactoryDAO.getUsuarioDAO();
			Usuario u = uDAO.encontrar(getName(), getClave());
			if (u == null) {
				addFieldError("name", getText("global.usuarioNoExixte"));
			} 
		}
	}

	private String name;
	private String clave;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getClave() {
		return clave;
	}

	public void setClave(String key) {
		this.clave = key;
	}

	public void setSession(Map<String, Object> session) {
		// TODO Auto-generated method stub
		this.session = session;
	}

	public Collection<Tesina> getCollTesis() {
		return collTesis;
	}

	public void setCollTesis(Collection<Tesina> collTesis) {
		this.collTesis = collTesis;
	}

}
